package com.xx.track_log.log;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

/**
 * @author fanjj
 * @date 2017/10/19
 */
public class TrackLogInterceptor implements MethodInterceptor {
    private TrackLogger trackLogger = TrackLogger.getInstance();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final static ObjectMapper jsonMapper = new ObjectMapper();

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            trackLogger.initialize(invocation.getThis().getClass().getSimpleName() + "." + invocation.getMethod().getName());
            logger.info("================== start  request processing ==================");
            logger.info("Before: request class: {}", invocation.getThis().getClass().getName());
            logger.info("Before: request method: {}", invocation.getMethod().getName());
            logger.info("Arguments: {}", jsonMapper.writeValueAsString(invocation.getArguments()));
            Object result = invocation.proceed();
            logger.info("After: result: {}", jsonMapper.writeValueAsString(result));
            return result;
        } finally {
            trackLogger.cleanUp();
            stopWatch.stop();
            logger.info("================== finish request processing in {} ms==================", stopWatch.getTotalTimeMillis());
        }
    }
}